package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 分页查询
     * @param categoryPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        //查询
        Page<Category> page=categoryMapper.page(categoryPageQueryDTO);
        //返回封装
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增分类
     * @param categoryDTO
     */
    @Override
    public void sava(CategoryDTO categoryDTO) {
        Category category = new Category();
        //拷贝
        BeanUtils.copyProperties(categoryDTO,category);

        //状态
        category.setStatus(StatusConstant.ENABLE);

        //创建时间、修改时间
//        category.setCreateTime(LocalDateTime.now());
//        category.setUpdateTime(LocalDateTime.now());
//
//        category.setCreateUser(BaseContext.getCurrentId());
//        category.setUpdateUser(BaseContext.getCurrentId());

        categoryMapper.insert(category);


    }

    /**
     * 根据id删除分类
     * @param id
     */
    @Override
    public void delete(Integer id) {
        categoryMapper.delete(id);
    }

    /**
     * 根据分类查询
     * @param type
     * @return
     */
    @Override
    public List<Category> list(Integer type) {
        List<Category> list=categoryMapper.list(type);
        return list;

    }

    /**
     * 启用禁用
     * @param status
     * @param id
     */
    @Override
    public void startOrClose(Integer status, Integer id) {
        log.info("启用禁用{}，{}",status,id);
        categoryMapper.startOrClose(status,id);
    }

    /**
     * 修改分类
     * @param categoryDTO
     */
    @Override
    public void updateByType(CategoryDTO categoryDTO) {
        log.info("修改分类");
        Category category = new Category();
        //copy
        BeanUtils.copyProperties(categoryDTO,category);

        category.setStatus(StatusConstant.ENABLE);
//        category.setUpdateTime(LocalDateTime.now());
//        category.setUpdateUser(BaseContext.getCurrentId());

        categoryMapper.updateByType(category);
    }
}
